/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-05-31 13:44:24
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2023-06-25 18:01:31
 * @FilePath: \greenbeeadmin\controllers\admin\service\userService.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package service

import (
	"greenbeeadmin/models"

	"github.com/beego/beego/v2/client/orm"
)

/**
 * @description: 菜单 service
 * @return {*}
 */
type MenuService struct {
	AdminBaseService
}

/**
 * @description: 获取菜单list数据
 * @param {map[string]string} params 搜索参数
 * @param {string} field 要查询的字段 全部数据传 “*”
 * @return {*}
 */
func (s *MenuService) GetAdminMenuList(params map[string]string, selectfield []string) ([]models.AdminMenu, error) {
	tableName := new(models.AdminMenu).GetTableName()
	var menus []models.AdminMenu
	parent_id, ok := params["parent_id"]
	where := "id > 0"
	if ok {
		where += " and parent_id ='" + parent_id + "'"
	}

	//查询数据
	o := orm.NewOrm()
	qb, _ := orm.NewQueryBuilder("mysql")
	// 构建查询对象
	qb.Select(selectfield...).
		From(tableName).
		Where(where).OrderBy("order_number").Desc()

	// 导出 SQL 语句
	sql := qb.String()

	// 执行 SQL 语句
	o.Raw(sql).QueryRows(&menus)

	return menus, nil
}

/**
 * @description: 获取菜单数据
 * @param {int} id
 * @return {*}
 */
func (s *MenuService) GetMenuData(id int) models.AdminMenu {
	var returndata models.AdminMenu
	o := orm.NewOrm()
	menu := models.AdminMenu{Id: id}
	err := o.Read(&menu, "Id")
	if err == orm.ErrNoRows {
		//fmt.Println("查询不到")
	} else if err == orm.ErrMissPK {
		//fmt.Println("找不到主键")
	} else {
		returndata = menu
	}
	return returndata
}

/**
 * @description: 菜单添加
 * @param {models.AdminMenu} menudata
 * @return {*}
 */
func (s *MenuService) MenuAdd(menudata models.AdminMenu) int64 {
	o := orm.NewOrm()
	id, err := o.Insert(&menudata)
	if err == nil {
		//fmt.Println(id)
	}
	return id
}

/**
 * @description: 菜单编辑
 * @param {models.AdminMenu} menudata
 * @param {int} id
 * @param {[]string} field
 * @return {*}
 */
func (s *MenuService) MenuEdit(menudata models.AdminMenu, id int, field []string) int64 {
	o := orm.NewOrm()
	menu := models.AdminMenu{Id: id}
	if o.Read(&menu, "Id") == nil {
		if num, err := o.Update(&menudata, field...); err == nil {
			//fmt.Println(num)
			return num
		}
	}
	return 0
}

/**
 * @description: 删除菜单（确保与其他表无关联，再删除）
 * @param {int} id
 * @return {*}
 */
func (s *MenuService) DeleteMenu(id int) int64 {
	o := orm.NewOrm()
	if num, err := o.Delete(&models.AdminMenu{Id: id}); err == nil {
		//fmt.Println(num)
		return num
	}
	return 0
}

// 菜单树形结构
type TreeAdminMenuData struct {
	Id            int    `json:"id"`
	CreatedAt     string `json:"CreatedAt"`
	UpdatedAt     string `json:"UpdatedAt"`
	DeletedAt     string `json:"DeletedAt" orm:"-"`
	AuthorityName string `json:"AuthorityName"`
	MenuIcon      string `json:"MenuIcon"`
	ParentId      int    `json:"ParentId"`
	OrderNumber   int    `json:"OrderNumber"`
	Status        int8   `json:"Status"`
	MenuUrl       string `json:"MenuUrl"`
	Authority     string `json:"Authority"`
	IsMenu        int8   `json:"IsMenu"`
	PrefixStr     string `json:"PrefixStr"` //树形结构前缀
}

/**
 * @description: 获取树形结构数据
 * @param {[]models.AdminMenu} data 要处理的数据
 * @param {int} parentId 起始的根节点id 示例 “-1”
 * @param {string} prefix 初始的拼接字符串 默认填 ""
 * @return {*}
 */
func (s *MenuService) GetTreeMenuData(data []models.AdminMenu, parentId int, prefix string) []TreeAdminMenuData {
	var returndata []TreeAdminMenuData
	if len(data) == 0 {
		return returndata
	}
	//顶级菜单
	if parentId == -1 {
		prefix = ""
	} else {
		prefix = prefix + "&nbsp; |- &nbsp;"
	}
	// 菜单数据处理
	for _, v := range data {
		if v.ParentId == parentId {
			treeAdminMenuData := TreeAdminMenuData{
				Id:        v.Id,
				CreatedAt: v.CreatedAt,
				UpdatedAt: v.UpdatedAt,
				//DeletedAt:     v.DeletedAt,
				AuthorityName: v.AuthorityName,
				MenuIcon:      v.MenuIcon,
				ParentId:      v.ParentId,
				OrderNumber:   v.OrderNumber,
				Status:        v.Status,
				MenuUrl:       v.MenuUrl,
				Authority:     v.Authority,
				IsMenu:        v.IsMenu,
				PrefixStr:     prefix,
			}
			// 组装当前菜单
			returndata = append(returndata, treeAdminMenuData)
			// 递归调用子菜单
			childdata := s.GetTreeMenuData(data, v.Id, prefix)
			if len(childdata) > 0 {
				returndata = append(returndata, childdata...)
			}
		}

	}
	return returndata

}

/**
 * @description: 获取菜单的所有下级菜单id
 * @param {int} id
 * @return {*}
 */
func (s *MenuService) GetMenuChildIds(id int) []int {
	var returndata []int
	var params map[string]string
	field := []string{"*"}
	menus, _ := s.GetAdminMenuList(params, field)
	if len(menus) > 0 {
		res := s.GetTreeMenuData(menus, id, "")
		for _, v := range res {
			returndata = append(returndata, v.Id)
		}
	}
	return returndata
}
